package aladyn.xmlparser;

import java.util.ArrayList;

import org.xml.sax.*;
import org.xml.sax.helpers.*;


public class LRSerializableXmlHandler extends DefaultHandler {

	/* 	<class_list>
	 * 		<class path="src.geometry.Point"/>
	 * 	</class_list> 
	 */
	public static final String class_listStr = "class_list";
	public static final String classStr = "class";
	public static final String pathStr = "path";
	
	private ArrayList<String> classes;
	private boolean inClassList;
	
	public LRSerializableXmlHandler() {
		super();
		classes = new ArrayList<String>();
		inClassList = false;
	}
	 
		
	public ArrayList<String> getClasses(){
		return classes;
	}
	 
	public void startDocument(){
		System.out.println("Start to parse XML document :");
	}
	 
	public void endDocument(){
		System.out.println("Fin\n");
	}
	 
	/**
	 * Actions a réaliser lors de la detection d'un nouvel element.
	 */
	public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attributs) 
	throws SAXException {	
		if(classStr.equals(localName)){
			if(!inClassList)
				throw new SAXException("Syntaxe error.");
			System.out.print("\t<" + classStr);
			String className = attributs.getValue(pathStr);
			if("".equals(className))
				throw new SAXException("Path can not be empty.");
			classes.add(className);
			
			for (int index = 0; index < attributs.getLength(); index++)  // on parcourt la liste des attributs
				System.out.print(" " +  attributs.getLocalName(index) + "=" + attributs.getValue(index));
			
		}else if(class_listStr.equals(localName)){
			System.out.print("<" + class_listStr);
			
			for (int index = 0; index < attributs.getLength(); index++)  // on parcourt la liste des attributs
				System.out.print(" " +  attributs.getLocalName(index) + "=" + attributs.getValue(index));
			
			System.out.print(">\n");
			inClassList = true;
		}else
			throw new SAXException("Unrecognized tag name.");

}


  
	/**
	 * Actions à réaliser lors de la détection de la fin d'un element.
	 */
	public void endElement(String nameSpaceURI, String localName, String rawName) {
		
		if(classStr.equals(localName)){
			System.out.print("/>\n");
		}
		if(class_listStr.equals(localName)){
			inClassList = false;
			System.out.print("<" + class_listStr + ">\n");
		}
	}

}
